<template>
  <div class="app-main-container">
    <div class="doumee-filter">
      <el-form inline>
        <el-form-item :label="$t('message.spmc')">
          <el-input
            v-model="filters.goodsName"
            @keyup.enter.native="getList(1)"
            :placeholder="$t('message.qsr') + $t('message.spmc')"
            clearable
          />
        </el-form-item>
        <el-form-item :label="$t('message.spzt2')">
          <el-select
            v-model="filters.checkGoodsStatus"
            @change="getList(1)"
            :placeholder="$t('message.qxz') + $t('message.spzt2')"
            clearable
          >
            <el-option
              v-for="item in filters.goodsStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button v-preventReClick type="primary" @click="getList(1)">{{
            $t("message.cz")
          }}</el-button>
          <el-button v-preventReClick @click="clear">{{
            $t("message.clear")
          }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="goosmanager-space-box">
      <div v-if="meta.indexOf('GoodsClassify') > -1" class="box-item goodstype">
        <div class="item-title df_sb">
          <span>{{ $t("message.spfl") }}</span>
          <el-button
            v-if="meta.indexOf('GoodsClassifyAdd') > -1"
            v-preventReClick
            type="primary"
            size="small"
            @click="addGoodsType"
          >
            {{ $t("message.tjfl") }}
          </el-button>
        </div>
        <div class="goods_category_list">
          <div
            v-for="(item, index) in goodsType"
            :key="item.id"
            :class="
              selectGoodsTypeInfo.id === item.id
                ? 'goodstype-item active'
                : 'goodstype-item'
            "
            @click="goodCateShow(item, index)"
          >
            <div
              class="df_sb"
              style="padding: 0 12px 0 6px"
              :class="item.isShowChild ? 'on' : ''"
            >
              <div class="title">
                <i
                  v-if="!item.isShowChild"
                  class="el-icon-arrow-down icon"
                  @click.stop="goodCateShow(item, index)"
                />
                <i
                  v-if="item.isShowChild"
                  class="el-icon-arrow-up icon"
                  @click.stop="goodCateShow(item, index)"
                />
                <span>{{ item.name }}</span>
              </div>
              <template>
                <el-popover
                  v-model="item.visible"
                  placement="right"
                  trigger="hover"
                  :hover="item.visible"
                >
                  <div class="popItems">
                    <div style="text-align: center">
                      <el-button
                        v-if="meta.indexOf('GoodsClassifyEdit') > -1"
                        v-preventReClick
                        size="mini"
                        type="text"
                        @click="visible = false"
                        @click.stop="toAddItem(item)"
                        >{{ $t("message.tjzfl") }}</el-button
                      >
                    </div>
                    <div style="text-align: center">
                      <el-button
                        v-if="meta.indexOf('GoodsClassifyEdit') > -1"
                        v-preventReClick
                        size="mini"
                        type="text"
                        @click="visible = false"
                        @click.stop="toEditGoodsType(item)"
                        >{{ $t("message.edit") }}</el-button
                      >
                    </div>
                    <div style="text-align: center">
                      <el-button
                        v-if="meta.indexOf('GoodsClassifyDel') > -1"
                        v-preventReClick
                        type="text"
                        size="mini"
                        class="red"
                        @click="visible = false"
                        @click.stop="toDeleteGoodsType(item)"
                        >{{ $t("message.del") }}</el-button
                      >
                    </div>
                  </div>
                  <el-button slot="reference" type="text" size="small">
                    <i class="el-icon-more" />
                  </el-button>
                </el-popover>
              </template>
            </div>
            <div v-show="item.isShowChild">
              <div
                v-for="child in item.item"
                :key="child.id"
                :class="{
                  goodsCateChild: selectGoodsTypeChild.id === child.id,
                }"
                style="padding: 0 12px 0 32px"
                class="df_sb"
                @click.stop="selectGoodsChild(child)"
              >
                <span>{{ child.name }}</span>
                <el-popover placement="right" trigger="hover">
                  <div class="popItems">
                    <div style="text-align: center">
                      <el-button
                        v-if="meta.indexOf('GoodsClassifyEdit') > -1"
                        v-preventReClick
                        size="mini"
                        type="text"
                        @click.stop="toEditGoodsType(child, item)"
                        >{{ $t("message.edit") }}</el-button
                      >
                    </div>
                    <div style="text-align: center">
                      <el-button
                        v-if="meta.indexOf('GoodsClassifyDel') > -1"
                        v-preventReClick
                        type="text"
                        size="mini"
                        class="red"
                        @click.stop="toDeleteGoodsType(child)"
                        >{{ $t("message.del") }}</el-button
                      >
                    </div>
                  </div>
                  <el-button slot="reference" type="text" size="small">
                    <i
                      class="el-icon-more"
                      :class="{
                        activeChildIcon: selectGoodsTypeChild.id === child.id,
                      }"
                    />
                  </el-button>
                </el-popover>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="goodsType.length" class="box-item goodsinfo">
        <el-button
          v-if="meta.indexOf('GoodsAdd') > -1"
          v-preventReClick
          type="primary"
          @click="addGoods"
          >{{ $t("message.xzsp") }}</el-button
        >
        <el-button
          v-if="meta.indexOf('GoodsImport') > -1"
          v-preventReClick
          type="primary"
          @click="inBatch"
          >{{ $t("message.pldr") }}</el-button
        >
        <!-- <el-button v-preventReClick type="primary" @click="showSKU">{{ $t('message.gggl') }}</el-button> -->
        <el-table
          ref="table"
          v-loading="listLoading"
          :data="goodsList"
          element-loading-text="Loading"
          border
          fit
          :header-row-class-name="'table-header'"
          class="doumee-element-table margin-t-20"
        >
          <el-table-column
            align="center"
            :label="$t('message.sptp')"
            min-width="80"
            prop="avatar"
          >
            <template slot-scope="scope">
              <el-image
                fit="contain"
                :src="scope.row.picture"
                :preview-src-list="[scope.row.picture]"
              />
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            :label="$t('message.spmc')"
            min-width="120"
            prop="name"
            show-overflow-tooltip
          />

          <el-table-column
            align="center"
            :label="$t('message.spfl')"
            show-overflow-tooltip
            prop="classifyName"
            min-width="80"
          />
          <el-table-column
            align="center"
            :label="$t('message.spkc')"
            prop="stock"
            min-width="80"
          />
          <el-table-column
            align="center"
            :label="$t('message.spjgy')"
            prop="price"
            min-width="120"
          />
          <el-table-column
            align="center"
            :label="$t('message.txm')"
            prop="barCode"
            show-overflow-tooltip
            min-width="120"
          />
          <el-table-column
            align="center"
            :label="$t('message.hyjg')"
            min-width="80"
          >
            <template slot-scope="scope">
              <el-popover
                :key="`popover-${scope.row.id}`"
                placement="top-start"
                width="300"
                trigger="click"
              >
                <div class="pre">
                  <div class="discount-title">{{ $t("message.hyzk") }}</div>
                  {{ discountInfo }}
                </div>
                <el-button
                  slot="reference"
                  v-preventReClick
                  type="text"
                  @click="toShow(scope)"
                  >{{ $t("message.djck") }}</el-button
                >
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            :label="$t('message.status')"
            min-width="80"
          >
            <template slot-scope="scope">
              {{
                scope.row.status == "1"
                  ? $t("message.shanjia")
                  : $t("message.xiajia")
              }}
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('message.caozuo')"
            min-width="150"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.status == '0'" class="flex-cc">
                <el-button
                  v-if="meta.indexOf('GoodsEdit') > -1"
                  v-preventReClick
                  type="text"
                  @click="toEdit(scope.row.id)"
                  >{{ $t("message.edit") }}</el-button
                >
                <el-button
                  v-if="meta.indexOf('GoodsUp') > -1"
                  v-preventReClick
                  type="text"
                  @click="editStatus(scope.row.id, scope.row.status)"
                  >{{
                    scope.row.status == "1"
                      ? $t("message.xiajia")
                      : $t("message.shanjia")
                  }}</el-button
                >
                <el-button
                  v-if="meta.indexOf('GoodsDel') > -1"
                  v-preventReClick
                  type="text"
                  class="secondColor"
                  @click="toDelete(scope.row.id)"
                  >{{ $t("message.del") }}</el-button
                >
              </div>
              <div v-if="scope.row.status == '1'" class="flex-cc">
                <el-button
                  v-if="meta.indexOf('GoodsDown') > -1"
                  v-preventReClick
                  type="text"
                  @click="editStatus(scope.row.id, scope.row.status)"
                  >{{
                    scope.row.status == "1"
                      ? $t("message.xiajia")
                      : $t("message.shanjia")
                  }}</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination_wrap">
          <el-pagination
            background
            @size-change="pageSizeChange"
            @current-change="getList"
            :current-page.sync="pagination.page"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pagination.rows"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount"
          >
          </el-pagination>
        </div>
        <!-- <Paginations :total="totalCount" :page="pagination.page" @current-change="getList" @SizeChange="pageSizeChange" /> -->
      </div>
    </div>
    <el-dialog
      :title="goodsTypeAddEdit ? $t('message.tjfl') : $t('message.bjfl')"
      :visible.sync="showAddGoodsType"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      width="600px"
      @close="cancelAddGoodsType"
    >
      <el-form
        ref="form"
        :model="goodsTypeInfo"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item :label="$t('message.sptp')" prop="catePic">
          <transition name="fade">
            <Cropper
              v-if="dialogCropperVisible"
              :option-img="optionImg"
              :fileinfo="fileinfo"
              use-type="GOODS_IMG"
              :fixed-number="[32, 32]"
              @formSubmit="cropperSubmit"
              @formClose="cropperClose"
            />
          </transition>
          <div class="df_ac">
            <el-upload
              class="device-uploader"
              accept=".jpg,.png"
              :auto-upload="false"
              :action="uploadFileUrl"
              :data="uploadParam"
              :show-file-list="false"
              :on-change="addFileChange"
            >
              <i class="el-icon-plus uploader-icon" />
              <div
                v-show="goodsTypeInfo.showPicture"
                class="file"
                :style="
                  'background-image: url(' + goodsTypeInfo.showPicture + ')'
                "
              >
                <div class="delete">
                  <i
                    class="el-icon-delete icon"
                    @click.stop="deleteDeviceConfigAddImage"
                  />
                </div>
              </div>
            </el-upload>
            <div class="placeholder9">
              <div>{{ $t("message.jycc") }}：{{ "100px X 100px" }}</div>
              <div>
                {{ $t("message.zctpsm") }}
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item v-if="goodsTypeInfo.parentId" :label="$t('message.gsfl')">
          <el-select v-model="goodsTypeInfo.parentId" style="width: 100%">
            <el-option
              v-for="op in goodsType"
              :key="op.id"
              :label="op.name"
              :value="op.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('message.flmc')" prop="name">
          <el-input
            v-model="goodsTypeInfo.name"
            :maxlength="50"
            :placeholder="$t('message.qsr') + $t('message.flmc')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.sort')" prop="sort">
          <el-input
            v-model="goodsTypeInfo.sort"
            :placeholder="$t('message.qsr') + $t('message.sort')"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddGoodsType = false">{{
          $t("message.qx")
        }}</el-button>
        <el-button
          v-preventReClick
          :loading="subLoading"
          type="primary"
          @click="confirmAddGoodsType"
          >{{ $t("message.qr") }}</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      :title="$t('message.pldr')"
      :visible.sync="isShow"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      width="30%"
      center
    >
      <el-upload
        ref="excel-upload-input"
        :action="uploadFileUrl"
        :limit="1"
        :data="uploadData"
        :auto-upload="true"
        accept=".xlsx, .xls"
        :on-change="fileChange"
        :on-success="handleSuccess"
        :on-error="handleError"
        :on-remove="removeFile"
        :file-list="fileList"
      >
        <el-button size="small" plain>{{ $t("message.xzwj") }}</el-button>
        <div slot="tip" class="el-upload__tip">
          {{ $t("message.znscbg") }}
        </div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button
          v-if="meta.indexOf('GoodsTemplateExcel') > -1"
          @click="downLoad"
          >{{ $t("message.xzmb") }}</el-button
        >
        <el-button v-preventReClick type="primary" @click="submit">{{
          $t("message.qr")
        }}</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="$t('message.drxxcw')"
      :visible.sync="isError"
      width="30%"
      center
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
    >
      <div v-for="(item, index) in errList" :key="index">{{ item }}</div>
      <span slot="footer" class="dialog-footer">
        <el-button v-preventReClick type="primary" @click="close">{{
          $t("message.qr")
        }}</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="$t('message.gggl')"
      :visible.sync="sku"
      width="800px"
      center
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
    >
      <el-table
        v-loading="listLoading"
        :data="skuNameList"
        element-loading-text="Loading"
        border
        fit
        :header-row-class-name="'table-header'"
        class="doumee-element-table margin-t-20"
      >
        <el-table-column
          align="center"
          :label="$t('message.ggm')"
          prop="name"
          min-width="200"
        />
        <el-table-column
          align="center"
          :label="$t('message.guige')"
          prop="vals"
          min-width="200"
        />
        <el-table-column
          :label="$t('message.caozuo')"
          min-width="250"
          align="center"
          fixed="right"
        >
          <template slot-scope="{ row }">
            <el-button
              v-preventReClick
              type="text"
              @click="toEditSkuName(row)"
              >{{ $t("message.edit") }}</el-button
            >
            <el-button v-preventReClick type="text" @click="toSkuVal(row)">{{
              $t("message.ggz")
            }}</el-button>
            <el-button
              v-preventReClick
              type="text"
              class="secondColor"
              @click="toDeleteSkuName(row.id)"
              >{{ $t("message.del") }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="addSkuAction">{{
          $t("message.xzgg")
        }}</el-button>
        <el-button v-preventReClick type="primary" @click="sku = false">{{
          $t("message.qr")
        }}</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="
        isNameAdd
          ? $t('message.add') + $t('message.ggmc')
          : $t('message.edit') + $t('message.ggmc')
      "
      :visible.sync="addSku"
      width="40%"
      center
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      @closed="closeSku"
    >
      <el-form
        ref="skuNameForm"
        :model="skuNameForm"
        label-width="auto"
        :rules="skuNameRules"
      >
        <el-form-item :label="$t('message.ggmc')" prop="name">
          <el-input
            v-model="skuNameForm.name"
            :placeholder="$t('message.qsr') + $t('message.ggmc')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.sort')" prop="sort">
          <el-input
            v-model="skuNameForm.sort"
            :placeholder="$t('message.qsr') + $t('message.sort')"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-preventReClick
          type="primary"
          @click="editAddSkuNameAction"
          >{{ $t("message.qr") }}</el-button
        >
        <el-button @click="addSku = false">{{ $t("message.qx") }}</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="$t('message.ggzgl')"
      :visible.sync="addSkuVal"
      width="40%"
      center
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      @close="getSkuNameList"
    >
      <el-form ref="skuValForm" v-model="skuValForm" inline>
        <el-form-item :label="$t('message.ggmc')" prop="name">
          {{ skuValForm.name }}
        </el-form-item>
        <div class="sku-title">{{ $t("message.ggz") }}</div>
        <el-form-item v-for="(item, index) in skuValList" :key="index">
          <el-input
            v-model="item.val"
            class="sku-value"
            :placeholder="$t('message.qsr') + $t('message.ggz')"
          />
          <el-input
            v-model="item.sort"
            class="sku-value"
            :placeholder="$t('message.qsr') + $t('message.sort')"
          />
          <el-button v-preventReClick type="text" @click="saveSkuVal(item)">{{
            $t("message.baocun")
          }}</el-button>
          <el-button
            v-if="item.id"
            type="text"
            class="secondColor"
            @click="delSkuVal(item.id)"
            >{{ $t("message.del") }}</el-button
          >
        </el-form-item>
        <div>
          <el-button type="text" @click="addSkuValAction()">{{
            $t("message.tijia")
          }}</el-button>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick type="primary" @click="addSkuVal = false">{{
          $t("message.qr")
        }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  uploadFile,
  getGoodsTemplateExcel,
  batchImportByExcel,
  goodsClassifySave,
  goodsClassifyListVenue,
  goodsClassifyEditSave,
  goodsClassifyRemove,
  goodsListVenue,
  goodsDiscount,
  goodsRemove,
  goodsStatusEdit,
  goodsStatusEdit1,
  goodsSkuNameEditSave,
  goodsSkuNameList,
  goodsSkuNameRemove,
  goodsSkuNameSave,
  goodsSkuValEditSave,
  goodsSkuValList,
  goodsSkuValRemove,
  goodsSkuValSave,
} from "@/api";
import { parseTime } from "@/utils/index";
import store from "@/store";
import Cropper from "@/components/cropper";
export default {
  name: "ManagerList",
  components: {
    Cropper,
  },
  data() {
    return {
      uploadParam: {
        folder: "GOODS_IMG",
      },
      dialogCropperVisible: false,
      optionImg: "",
      fileinfo: {},
      modalDialog: store.getters.dialog,
      subLoading: false,
      meta: [],
      fileList: [],
      fileUrl: "",
      uploadData: {
        folder: "PUBLIC_IMG",
        type: "",
      },
      isError: false,
      errList: [],
      uploadFileUrl: uploadFile,
      isShow: false,
      totalCount: 0,
      listLoading: false,
      goodsList: [],
      pagination: {
        page: 1,
        rows: 10,
      },
      discountInfo: "",
      goodsTypeAddEdit: true,
      showAddGoodsType: false,
      activeGoodsType: {},
      goodsType: [],
      goodsTypeInfo: {
        name: "",
        picture: "",
        sort: "",
        saleType: [],
        venueId: sessionStorage.getItem("venueId"),
      },
      selectGoodsTypeInfo: {},
      selectGoodsTypeChild: {},
      filters: {
        goodsName: "",
        checkGoodsStatus: null,
        goodsStatus: [
          { value: "", label: this.$t("message.qb") },
          { value: "1", label: this.$t("message.shanjia") },
          { value: "0", label: this.$t("message.xiajia") },
        ],
      },
      saleTypes: [
        { name: this.$t("message.sp"), id: "0" },
        { name: this.$t("message.caipin"), id: "1" },
      ],
      sku: false,
      addSku: false,
      showChildId: "",
      rules: {
        saleType: [
          {
            required: true,
            message: this.$t("message.qxz") + this.$t("message.xsqd"),
            trigger: "change",
          },
        ],
        name: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.flmc"),
            trigger: "blur",
          },
        ],
        sort: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.sort"),
            trigger: "blur",
          },
        ],
      },
      skuRules: {},
      skuNameList: [],
      isNameAdd: false,
      skuNameForm: {
        name: "",
        sort: "",
      },
      skuNameRules: {
        name: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.ggmc"),
            trigger: "blur",
          },
        ],
        sort: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.sort"),
            trigger: "blur",
          },
        ],
      },
      addSkuVal: false,
      skuValForm: {},
      skuValList: [],
    };
  },

  created(e) {
    this.meta = this.$route.meta.buttons || [];
    if (this.$route.query.page) {
      //   console.log("🚀 ~ created ~ page:", this.$route.query)
      let pages = Number(this.$route.query.page);
      this.$set(this.pagination, "page", pages);
      this.selectGoodsTypeInfo.id = this.$route.query.showChildId;
      this.showChildId = this.$route.query.showChildId;
    }
    this.getClassifyList();
  },
  activated() {
    this.$refs.table.doLayout();
  },
  methods: {
    showSKU() {
      this.sku = true;
      this.getSkuNameList();
    },
    getSkuNameList() {
      goodsSkuNameList({
        param: {
          venueId: sessionStorage.getItem("venueId"),
          saleType: 0,
        },
      }).then((res) => {
        // console.log(res);
        if (res.errorCode === "000000") {
          this.skuNameList = res.recordList;
        }
      });
    },
    addSkuAction() {
      this.isNameAdd = true;
      this.addSku = true;
    },
    toEditSkuName(row) {
      this.addSku = true;
      this.isNameAdd = false;
      this.skuNameForm = { ...row };
    },
    editAddSkuNameAction() {
      // console.log(this.skuNameForm);
      this.$refs.skuNameForm.validate((v) => {
        if (v) {
          const skuNameAction = this.isNameAdd
            ? goodsSkuNameSave
            : goodsSkuNameEditSave;
          skuNameAction({
            param: {
              ...this.skuNameForm,
              venueId: sessionStorage.getItem("venueId"),
            },
          }).then((res) => {
            if (res.errorCode !== "000000") return;
            this.addSku = false;
            this.getSkuNameList();
          });
        }
      });
    },
    // 商品图片上传成功
    uploadSuccess(response, file, fileList) {
      this.param.picture = fileList[0].response.insertUrl;
      this.$refs.form.clearValidate();
    },
    // 上传图片，开始裁剪
    async addFileChange(file) {
      // 上传，拿到file文件
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw);
        this.fileinfo = file.raw;
        this.dialogCropperVisible = true;
      });
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.goodsTypeInfo, "showPicture", config.showUrl);
        this.$set(this.goodsTypeInfo, "picture", config.insertUrl);
        this.fileinfo = config;
        // this.$refs.ruleForm.clearValidate();
        this.dialogCropperVisible = false;
      } else {
        this.$message.error(config.msg || this.$t("message.scsb"));
        this.$refs.form.clearValidate();
        this.dialogCropperVisible = false;
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false;
    },
    // 商品图片移除
    deleteDeviceConfigAddImage(file, fileList) {
      this.$set(this.goodsTypeInfo, "picture", "");
      this.$set(this.goodsTypeInfo, "showPicture", "");
    },
    closeSku() {
      // console.log(this.skuNameForm);
      this.skuNameForm = {
        name: "",
        sort: "",
      };
      // console.log(this.skuNameForm);
    },
    toDeleteSkuName(id) {
      goodsSkuNameRemove({ param: { id } }).then((res) => {
        if (res.errorCode === "000000") {
          this.$message.success(this.$t("message.delcg"));
          this.getSkuNameList();
        } else {
          this.$message.success(res.errorMsg);
        }
      });
    },
    toSkuVal(row) {
      this.skuValForm = row;
      this.addSkuVal = true;
      this.getSkuValList();
    },
    getSkuValList() {
      goodsSkuValList({
        param: { goodsSkuId: this.skuValForm.id },
      }).then((res) => {
        if (res.errorCode === "000000") {
          this.skuValList = res.recordList;
        }
      });
    },
    addSkuValAction() {
      this.skuValList.push({
        val: "",
        sort: "",
      });
    },
    saveSkuVal(item) {
      if (!item.val) {
        this.$message.error(this.$t("message.qsr") + this.$t("message.ggz"));
        return;
      }
      if (!item.sort) {
        this.$message.error(this.$t("message.qsr") + this.$t("message.sort"));
        return;
      }
      if (item.id) {
        // 编辑
        goodsSkuValEditSave({
          param: {
            ...item,
          },
        }).then((res) => {
          if (res.errorCode === "000000") {
            this.$message.success(this.$t("message.editcg"));
            this.getSkuValList();
          }
        });
      } else {
        // 新增
        goodsSkuValSave({
          param: {
            ...item,
            goodsSkuId: this.skuValForm.id,
          },
        }).then((res) => {
          if (res.errorCode === "000000") {
            this.$message.success(this.$t("message.addcg"));
            this.getSkuValList();
          }
        });
      }
    },
    delSkuVal(id) {
      goodsSkuValRemove({ param: { id } }).then((res) => {
        if (res.errorCode === "000000") {
          this.$message.success(this.$t("message.delcg"));
          this.getSkuValList();
        }
      });
    },
    // 场馆端商品分类列表
    getClassifyList(e) {
      goodsClassifyListVenue({
        param: {
          venueId: sessionStorage.getItem("venueId"),
          saleType: 0,
        },
      })
        .then((res) => {
          this.listLoading = false;
          if (res.errorCode !== "000000") return;
          let goodsType = res.recordList || [];
          let listIndex = 0;
          console.log("🚀 ~ this.goodsType.forEach ~ item:000", res.recordList);
          goodsType.forEach((item, index) => {
            item.isShowChild = false;
            if (this.showChildId && item.id === this.showChildId) {
              listIndex = index;
            }
          });
          //   之前的逻辑
          //   this.goodsType.forEach((item, index) => {
          //     item.isShowChild = false
          //     if (this.showChildId && item.id === this.showChildId) {
          //       listIndex = index
          //     }
          //   })
          goodsType[listIndex].isShowChild = true;
          this.goodsType = goodsType;
          if (goodsType.length > 0) {
            if (this.selectGoodsTypeInfo.id) {
              this.selectGoodsTypeInfo = this.goodsType.find(
                (item) => item.id === this.selectGoodsTypeInfo.id
              );
              console.log("this.selectGoodsTypeInfo", this.selectGoodsTypeInfo);
            } else {
              this.selectGoodsTypeInfo = goodsType[listIndex];
              this.showChildId = goodsType[listIndex].id;
            }
            console.log("🚀 ~ this.goodsType.forEach ~  listIndex:", listIndex);
            this.selectGoodsTypeChild = goodsType[listIndex];
            this.getList();
          }
        })
        .catch(() => {});
    },
    // 场馆端商品分类列表
    getList(page) {
      const { pagination } = this;
      if (page) {
        pagination.page = page;
        this.pagination.page = page;
      }
      pagination.firstQueryTime = parseTime(new Date());
      this.listLoading = true;
      goodsListVenue({
        pagination,
        param: {
          classifyId: this.selectGoodsTypeChild.id,
          name: this.filters.goodsName,
          status: this.filters.checkGoodsStatus,
          venueId: sessionStorage.getItem("venueId"),
        },
      })
        .then((res) => {
          this.listLoading = false;
          if (res.errorCode !== "000000") return;
          this.goodsList = res.recordList;
          this.totalCount = res.totalCount;
          this.$refs.table.doLayout();
          if (
            res.totalCount &&
            res.recordList.length === 0 &&
            pagination.page > 1
          ) {
            this.getList(Math.ceil(res.totalCount / pagination.rows));
          }
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    pageSizeChange(val) {
      this.pagination.rows = val;
      this.getList(1);
    },
    toShow(scope) {
      // 展示折扣详情
      // list
      goodsDiscount({ param: { id: scope.row.id } }).then((res) => {
        if (res.errorCode !== "000000") return;
        const discountInfo = res.recordList;
        var memprice = "";
        discountInfo.forEach((item) => {
          memprice = memprice + item.cardName + ":" + item.memberPrice + " \n ";
        });
        this.discountInfo = memprice;
        console.log(this.discountInfo);
      });
    },
    // 启用或禁用
    editStatus(id, status) {
      if (status === "0") {
        goodsStatusEdit({
          param: {
            id,
          },
          userId: sessionStorage.getItem("userId"),
        })
          .then((res) => {
            if (res.errorCode === "000000") {
              this.getList();
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        goodsStatusEdit1({
          param: {
            id,
          },
          userId: sessionStorage.getItem("userId"),
        })
          .then((res) => {
            if (res.errorCode === "000000") {
              this.getList();
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    // 删除
    toDelete(id) {
      const that = this;
      this.$confirm(this.$t("message.scsptc"), this.$t("message.ts"), {
        confirmButtonText: this.$t("message.qd"),
        cancelButtonText: this.$t("message.qx"),
        type: "warning",
        callback: () => {},
        beforeClose: (action, ctx, close) => {
          if (action !== "confirm") {
            close();
            return;
          }
          ctx.confirmButtonLoading = true;
          goodsRemove({
            param: { id },
            userId: sessionStorage.getItem("userId"),
          })
            .then((res) => {
              ctx.confirmButtonLoading = false;
              close();
              if (res.errorCode === "000000") {
                that.$message.success(this.$t("message.delcg"));
                that.getList();
              }
            })
            .catch(() => {
              ctx.confirmButtonLoading = false;
            });
        },
      }).finally(() => {});
    },
    addGoodsType() {
      this.goodsTypeAddEdit = true;
      this.showAddGoodsType = true;
    },
    cancelAddGoodsType() {
      this.goodsTypeInfo = { name: "", sort: "", saleType: [] };
      this.$refs.form.clearValidate();
    },
    confirmAddGoodsType() {
      if (this.goodsTypeAddEdit) {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.subLoading = true;
            goodsClassifySave({
              param: {
                venueId: sessionStorage.getItem("venueId"),
                name: this.goodsTypeInfo.name,
                sort: this.goodsTypeInfo.sort,
                picture: this.goodsTypeInfo.picture,
                parentId: this.goodsTypeInfo.parentId || null,
                saleType: 0,
                // saleType: this.goodsTypeInfo.saleType.join(',')
              },
            }).then(
              (res) => {
                if (res.errorCode !== "000000") return;
                this.showAddGoodsType = false;
                this.subLoading = false;
                this.getClassifyList();
              },
              () => {
                this.subLoading = false;
              }
            );
          } else {
            this.subLoading = false;
            console.log("error submit!!");
            return false;
          }
        });
      } else {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.subLoading = true;
            goodsClassifyEditSave({
              param: {
                id: this.goodsTypeInfo.id,
                classifyName: this.goodsTypeInfo.name,
                sort: this.goodsTypeInfo.sort,
                picture: this.goodsTypeInfo.picture,
                parentId: this.goodsTypeInfo.parentId || null,
                saleType: this.goodsTypeInfo.saleType.join(","),
              },
            })
              .then((res) => {
                this.subLoading = false;
                if (res.errorCode !== "000000") return;
                this.showAddGoodsType = false;
                this.getClassifyList();
              })
              .catch(() => {
                this.subLoading = false;
              });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      }
    },
    selectGoodsType(item) {
      this.selectGoodsTypeInfo = item;
      // this.showGoodsListByType()
    },
    selectGoodsChild(item) {
      console.log("item", item);
      this.selectGoodsTypeChild = item;
      this.showGoodsListByType();
    },
    goodCateShow(item, index) {
      console.log("🚀 ~ goodCateShow ~ item:", item);
      let { goodsType } = this;
      this.showChildId = item.id;
      const arr = [...goodsType];
      arr.forEach((i) => {
        if (i.id === item.id) {
          i.isShowChild = !i.isShowChild;
        }
      });
      this.selectGoodsTypeInfo = item;
      this.selectGoodsTypeChild = item;
      this.getList();
      goodsType = arr;
      this.$forceUpdate();
    },
    showGoodsListByType() {
      this.getList();
    },
    toAddItem(item) {
      this.goodsTypeInfo = {
        parentName: item.name,
        parentId: item.id,
        saleType: item.saleType.split(","),
      };
      this.goodsTypeAddEdit = true;
      this.showAddGoodsType = true;
    },
    toEditGoodsType(item, parent) {
      this.goodsTypeInfo = { ...item, saleType: item.saleType.split(",") };
      console.log(item, parent);
      this.goodsTypeAddEdit = false;
      this.showAddGoodsType = true;
    },
    toDeleteGoodsType(item) {
      const that = this;
      this.$confirm(this.$t("message.scspfltc"), this.$t("message.ts"), {
        confirmButtonText: this.$t("message.qd"),
        cancelButtonText: this.$t("message.qx"),
        type: "warning",
        callback: () => {},
        beforeClose: (action, ctx, close) => {
          if (action !== "confirm") {
            close();
            return;
          }
          ctx.confirmButtonLoading = true;
          goodsClassifyRemove({ param: { id: item.id } })
            .then((res) => {
              ctx.confirmButtonLoading = false;
              close();
              if (res.errorCode === "000000") {
                that.$message.success(this.$t("message.delcg"));
                that.getClassifyList();
              }
            })
            .catch(() => {
              ctx.confirmButtonLoading = false;
            });
        },
      }).finally(() => {});
    },
    inBatch() {
      this.isShow = true;
    },
    downLoad() {
      getGoodsTemplateExcel({ param: { type: 0 } })
        .then((res) => {
          if (res.errorCode === "000000") {
            window.open(res.record, "_blank");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    submit() {
      if (this.fileUrl.length === 0) {
        this.$message.error(this.$t("message.qxxzwj"));
        return;
      }
      // excelPath
      batchImportByExcel({
        param: { excelPath: this.fileUrl },
        userId: sessionStorage.getItem("userId"),
      })
        .then((res) => {
          console.log(res);
          this.isShow = false;
          if (res.errorCode === "000000") {
            this.getClassifyList();
            // this.uploadFileUrl = ''
            this.fileList = [];
            this.fileUrl = "";
            if (res.record.errList.length) {
              this.errList = res.record.errList;
              this.isError = true;
            }
          }
        })
        .catch(() => {
          this.getClassifyList();
        });
    },
    close() {
      this.isError = false;
    },
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      this.$notify.warning({
        title: this.$t("message.jingao"),
        message:
          this.$t("message.znxzygwj") +
          ` ${files.length + fileList.length} ` +
          this.$t("message.gei"),
      });
    },
    // 文件状态改变时的钩子
    fileChange(file, fileList) {
      console.log("change", file, fileList);
      // const formDate = new FormData()
      // formDate.append('file', file)
      // Axios.post(this.uploadFileUrl, formDate).then(res => {
      //   console.log(res)
      // })
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUploadFile(file) {
      console.log("before upload");
      // const extension = file.name.substring(file.name.lastIndexOf('.') + 1)
      const size = file.size / 1024 / 1024;
      if (size > 10) {
        this.$notify.warning({
          title: this.$t("message.jingao"),
          message: this.$t("message.wjdabndy10"),
        });
      }
    },
    // 文件上传成功时的钩子
    handleSuccess(res, file, fileList) {
      // console.log('成功', fileList)
      this.fileList = fileList;
      this.fileUrl = file.response.showUrl;
      console.log(this.fileUrl);
    },
    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
      // console.log(this.$t('message.cw'))
      debugger;
      this.$notify.error({
        title: this.$t("message.cw"),
        message: this.$t("message.wjscsb"),
      });
      console.log(err, file, fileList);
    },
    // 文件移除
    removeFile(file, fileList) {
      // console.log('移除')
      this.fileUrl = "";
    },
    addGoods() {
      this.$router.push({ name: "GoodsAdd" });
    },
    handleBack(e) {
      console.log(e, "222");
    },
    // 编辑
    toEdit(id) {
      this.$router.push({
        name: "GoodsAdd",
        query: {
          id: id,
          page: this.pagination.page,
          showChildId: this.selectGoodsTypeInfo.id,
        },
      });
    },
    clear() {
      this.filters.goodsName = "";
      this.filters.checkGoodsStatus = null;
      this.pagination.page = 1;
      this.getList(1);
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.pagination_wrap {
  display: flex;
  // justify-content: flex-end;
  align-items: center;
  padding: 20px;
  .el-pagination {
    height: 36px;
    display: flex;
    ::v-deep span {
      height: 36px !important;
      line-height: 36px !important;
    }
    ::v-deep button {
      height: 36px !important;
      line-height: 36px !important;
      min-width: 36px;
    }
    ::v-deep li {
      height: 36px !important;
      line-height: 36px !important;
      min-width: 36px !important;
    }
    ::v-deep .el-pagination__editor {
      height: 36px !important;
      line-height: 36px !important;
      margin: 0 5px;
    }
    ::v-deep .el-input__inner {
      height: 36px !important;
      line-height: 36px !important;
      padding: 0;
    }
    ::v-deep .el-pagination__total {
      height: 36px !important;
      line-height: 36px !important;
    }
  }
  .el-pagination__total {
    height: 36px !important;
    line-height: 36px !important;
  }
}
.el-select .el-input__inner {
  &:focus {
    border-color: $primaryColor !important;
  }
}
.division-line {
  text-align: center;
  display: inline-block;
  color: #999;
  width: 20px;
  margin-right: 10px;
}
.goosmanager-space-box {
  display: flex;
  position: relative;
  height: calc(100% - 78px);
  box-sizing: border-box;
  .box-item {
    .goods_category_list {
      height: 560px;
      overflow-y: auto;
    }
    // position: absolute;
    .goodstype-item {
      background-color: #f7f7f7;
      padding: 8px 0px;
      border-radius: 4px;
      margin-top: 5px;
      cursor: pointer;
      /* display: flex;
       margin-right: 10px;
      align-items: center;
      justify-content: space-between; */
      .icon {
        padding: 4px;
      }
      .popItems {
        display: flex;
        flex-direction: column;
        // align-items: flex-start;
        // justify-content: flex-start;
      }
    }
    .goodstype-item.active {
      background-color: #f4f7fc;
      border-radius: 4px;
    }
    .goodsCateChild {
      background-color: $primaryColor;
      color: #fff;
    }
    .activeChildIcon {
      color: #fff;
    }
    .add-goodstype-btn {
      // position: absolute;
      // bottom: 0;
      // left: 55px;
      width: 150px;
      margin-top: 20px;
      margin-left: 55px;
    }
  }
  .box-item.goodstype {
    width: 220px;
    // padding-right: 30px;
    margin-right: 20px;
    height: 100%;
    overflow-y: auto;
  }
  .box-item.goodsinfo {
    flex: 1;
    height: 100%;
    overflow-y: auto;
    min-width: 0;
  }
}
.pre {
  white-space: pre;
  .discount-title {
    color: #303133;
    font-size: 16px;
    margin-bottom: 12px;
  }
}
.sku-title {
  height: 24px;
  line-height: 24px;
  margin-bottom: 10px;
  font-size: 14px;
  font-weight: 500;
}
.sku-value {
  margin-right: 10px;
  width: 180px;
}
@import "@/styles/variables.scss";
.device-uploader {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
/**
*/
</style>
